package com.wwl.cms.service;

import com.wwl.cms.basic.utils.R;
import com.wwl.cms.config.oauth2.TokenGenerator;
import com.wwl.cms.entity.SysUserTokenEntity;
import com.wwl.cms.entity.UserBean;
import com.wwl.cms.repository.SysUserTokenRepository;
import com.wwl.cms.repository.UserInfoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @author wwl
 * @version 1.0
 * @date 2021/4/29 15:13
 * @description:
 */
@Service
public class ShiroService {
    @Autowired
    private SysUserTokenRepository sysUserTokenRepository;
    @Autowired
    private UserInfoRepository userInfoRepository;
    //12小时后过期
    private final static int EXPIRE = 3600 * 12;

    /**
     * 根据token查询用户信息
     * @param token
     * @return
     */
    public SysUserTokenEntity findByToken(String token){
       return sysUserTokenRepository.findByToken(token);
    }

    /**
     * 根据id查询用户信息
     * @param userId
     * @return
     */
    public UserBean findById(Long userId){
       return userInfoRepository.findFirstById(userId);
    }

    /**
     * 创建token
     * @param userId
     * @return
     */
    @Transactional
    public R createToken (Long userId){
        //生成一个token
        String token = TokenGenerator.generateValue();

        //当前时间
        Date now = new Date();
        //过期时间
        Date expireTime = new Date(now.getTime() + EXPIRE * 1000);

        //判断是否生成过token
        SysUserTokenEntity tokenEntity = sysUserTokenRepository.findByUserId(userId);
        if(tokenEntity == null){
            tokenEntity = new SysUserTokenEntity();
            tokenEntity.setUserId(userId);
            tokenEntity.setToken(token);
            tokenEntity.setUpdateTime(now);
            tokenEntity.setExpireTime(expireTime);
        }
        //保存token
        sysUserTokenRepository.save(tokenEntity);
        //R r = R.ok().put("token", token).put("expire", EXPIRE);
        return new R(token);
    }


}
